/**
 * create by young (young2f@outlook.com) on 2020/10/30
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Form, Input, Popconfirm, Table} from 'antd';

import styles from '../index.less';
import {FormField, FormLayout, ModalView} from 'antd-extra';
import ModalCreateTenant from './ModalCreateTenant';
import ViewTitle from '../../components/ViewTitle';
import ProductionElement from '../../components/ProductionElement';
import ComponentBase from '../../components/Base/ComponentBase';
import notify from '../../components/NotificationExtra';

const _ = require('lodash');
const moment = require('moment');

@Form.create()
@connect(({global, tenant}) => ({...global, ...tenant}))
export default class TenantMgr extends ComponentBase {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.onLoadData().then(res => this.setState(res));
  }

  async onLoadData() {
    const res = await this.props.dispatch({
      type: 'tenant/findTenants',
      payload: {},
    });
    console.log('获取租户：', res);
    return res;
  };

  create = () => {
    ModalView.open(ModalCreateTenant,
      {title: '新建租户', width: '720px'},
      {
        dispatch: this.props.dispatch,
        result: payload => {
          this.props.dispatch(
            {type: 'tenant/createTenant', payload},
          ).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        },
      },
    );
  };
  detail = (tenant) => {
    ModalView.open(ModalCreateTenant,
      {title: '编辑租户', width: '720px'},
      {
        dispatch: this.props.dispatch,
        tenant,
        result: data => {
          data.tenantType = tenant.tenantType;
          this.props.dispatch(
            {type: 'tenant/updateTenant', payload: data},
          ).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        },
      },
    );
  };
  // onRemove = (record) => {
  //   const {tenantCode} = record;
  //   this.props.dispatch({
  //     type: 'tenant/removeTenant',
  //     payload: {tenantCode},
  //   }).then(res => {
  //     this.requestReturn(res);
  //     this.componentDidMount();
  //   });
  // };
  onDelete = (record) => {
    const {tenantCode} = record;
    this.props.dispatch({
      type: 'tenant/deleteTenant',
      payload: {tenantCode},
    }).then(res => {
      this.requestReturn(res);
      this.componentDidMount();
    });
  };
  updateSU = () => {
    this.props.form.validateFields(async (err, values) => {
      if (err) {
        const {code} = err;
        code && code.errors && code.errors.forEach(item => {
          notify({message: item, type: 'error'});
        });
        return;
      }
      const {username, password} = values;

      const user = this.getLoginInfo();
      const {_id} = user;
      const pwd = this.getCryptoPassword(password);
      const body = {_id, username, password: pwd};
      this.props.dispatch({type: 'user/updateSu', payload: body}).then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
    });
  };

  /**
   *  tenantName: { type: 'string' },
   tenantAddress: { type: 'string' },
   tenantCountry: { type: 'string' },
   tenantProvince: { type: 'string' },
   tenantCity: { type: 'string' },
   tenantInvalidData: { type: 'date' },
   tenantAdminUser: { type: 'string' },
   tenantAdminPassword: { type: 'string' },
   isChildren: { type: 'boolean' },
   fatherTenant: { type: 'string' },
   * @returns {*[]}
   */
  columns = () => {
    const temp = [
      {
        title: '租户', dataIndex: 'tenantName',
        render: (value, record) => {
          const {tenantCode, tenantName} = record;
          return (
            <ProductionElement code={tenantCode} name={tenantName}></ProductionElement>
          );
        },
      },
      {
        title: '简称', dataIndex: 'tenantShortName'
      },
      {
        title: '行政区域', dataIndex: 'tenantCity',  render: (value, record) => {
          const {tenantCity} = record;
          return (<div>{`${tenantCity}`}</div>);
        },
      },
      {title: '管理员', dataIndex: 'tenantAdminUsername', key: 'tenantAdminUsername'},
      {
        title: '创建时间', dataIndex: 'createdTs',  render: value => {
          return (<div>{moment(value).format('YYYY-MM-DD HH:mm:ss')}</div>);
        },
      },
      {
        title: '最大关联公司数量', dataIndex: 'maxRelatingTenant',
      },
      {
        title: '最大用户数量', dataIndex: 'maxUser',
      },
      {
        title: '失效时间', dataIndex: 'tenantInvalidData',  render: value => {
          return (<div>{moment(value).format('YYYY-MM-DD')}</div>);
        },
      },
      {
        title: '是否删除', dataIndex: 'isDeleted',  render: value => {
          return value ? '是' : '否';
        },
      },
      {
        title: '操作', dataIndex: 'opt',
        render: (value, record) => {
          const {isDeleted} = record;
          return (
            <span>
         {<a style={{marginRight: '6px'}} onClick={() => this.detail(record)}>详情</a>}
              {!isDeleted && <Popconfirm
                title="确认删除"
                onConfirm={this.onDelete.bind(this, record)}
                okText="是"
                cancelText="否"
              >
                <a disabled={isDeleted}>删除</a>
              </Popconfirm>
              }
              {isDeleted && <Popconfirm
                title="彻底删除后所有数据将不可恢复，确认删除？"
                onConfirm={this.onDelete.bind(this, record)}
                okText="是"
                cancelText="否"
              >
                <a>彻底删除</a>
              </Popconfirm>
              }
            </span>
          );
        },
      },

    ];
    return temp;
  };

  render() {
    const {tenants, form} = this.props;
    const user = this.getLoginInfo();
    const {username, password} = user;
    return (<Form className={styles.content}>
      <ViewTitle
        title={'租户管理'}
        actions={[
          <Button type={'primary'} onClick={this.create.bind(this)}>新建</Button>,
        ]}
      >
      </ViewTitle>
      <Table
        className={styles.antTable}
        bordered={true}
        columns={this.columns()}
        dataSource={tenants}
        // scroll={{ x: true }}
        pagination={true}
      >
      </Table>
      <ViewTitle title={'超级管理员信息'}
                 actions={<Button type={'primary'} onClick={this.updateSU.bind(this)}>更新</Button>}
      ></ViewTitle>
      {
        <FormLayout form={form} cols={2}>
          <FormField
            label={'用户名'}
            name={'username'}
            required={true}
            initialValue={username}
          >
            <Input
              style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'密码'}
            name={'password'}
            required={true}
            initialValue={password}
          >
            <Input
              type={'password'}
              style={{width: '100%'}}
            ></Input>
          </FormField>
        </FormLayout>
      }
    </Form>);
  }
}
